package handlers

import (
	"database/sql"
	"jz/config"
	"log"
	"net/http"
)

type StatisticsHandler struct {
	db        *sql.DB
	cfg       *config.Config
	tableName string
}

type MonthlyStats struct {
	MonthlyIncome  []float64 `json:"monthlyIncome"`
	MonthlyExpense []float64 `json:"monthlyExpense"`
}

type TypeDistribution struct {
	Value float64 `json:"value"`
	Name  string  `json:"name"`
	Type  string  `json:"type"`   // 添加类型字段：income 或 expense
	Color string  `json:"color"`  // 添加颜色字段
}

type StatisticsResponse struct {
	MonthlyStats     MonthlyStats       `json:"monthlyStats"`
	TypeDistribution []TypeDistribution `json:"typeDistribution"`
}

func NewStatisticsHandler(db *sql.DB, cfg *config.Config, tableName string) *StatisticsHandler {
	return &StatisticsHandler{
		db:        db,
		cfg:       cfg,
		tableName: tableName,
	}
}

func (h *StatisticsHandler) HandleStatistics(w http.ResponseWriter, r *http.Request) {
	// 打印请求信息
	log.Printf("收到统计请求 - URL: %s, 方法: %s\n", r.URL.String(), r.Method)

	if r.Method != http.MethodGet {
		log.Printf("错误：不支持的请求方法 %s\n", r.Method)
		writeJSON(w, map[string]interface{}{
			"success": false,
			"message": "方法不允许",
		}, http.StatusMethodNotAllowed)
		return
	}

	year := r.URL.Query().Get("year")
	log.Printf("请求参数 - 年份: %s\n", year)

	if year == "" {
		log.Println("错误：缺少年份参数")
		writeJSON(w, map[string]interface{}{
			"success": false,
			"message": "缺少年份参数",
		}, http.StatusBadRequest)
		return
	}

	// 查询月度收支数据
	monthlyQuery := `
        SELECT month, SUM(CASE WHEN type = 'income' THEN money ELSE 0 END) as income,
               SUM(CASE WHEN type = 'expense' THEN money ELSE 0 END) as expense
        FROM ` + h.tableName + `
        WHERE year = ? AND del = 0
        GROUP BY month
        ORDER BY month`

	log.Printf("执行SQL查询 - 月度统计:\n%s\n参数: [%s]\n", monthlyQuery, year)

	rows, err := h.db.Query(monthlyQuery, year)
	if err != nil {
		log.Printf("月度统计查询出错: %v\n", err)
		writeJSON(w, map[string]interface{}{
			"success": false,
			"message": "获取月度统计数据失败: " + err.Error(),
		}, http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	if r.Method != http.MethodGet {
		writeJSON(w, map[string]interface{}{
			"success": false,
			"message": "方法不允许",
		}, http.StatusMethodNotAllowed)
		return
	}

	// 获取查询参数中的年份
	year = r.URL.Query().Get("year")
	if year == "" {
		writeJSON(w, map[string]interface{}{
			"success": false,
			"message": "缺少年份参数",
		}, http.StatusBadRequest)
		return
	}

	// 查询月度收支数据
	monthlyStats, err := h.getMonthlyStats(year)
	if err != nil {
		writeJSON(w, map[string]interface{}{
			"success": false,
			"message": "获取月度统计数据失败: " + err.Error(),
		}, http.StatusInternalServerError)
		return
	}

	// 查询类型分布数据
	typeDistribution, err := h.getTypeDistribution(year)
	if err != nil {
		writeJSON(w, map[string]interface{}{
			"success": false,
			"message": "获取类型分布数据失败: " + err.Error(),
		}, http.StatusInternalServerError)
		return
	}

	// 返回统计数据
	writeJSON(w, map[string]interface{}{
		"success": true,
		"data": StatisticsResponse{
			MonthlyStats:     monthlyStats,
			TypeDistribution: typeDistribution,
		},
	}, http.StatusOK)
}

func (h *StatisticsHandler) getMonthlyStats(year string) (MonthlyStats, error) {
	stats := MonthlyStats{
		MonthlyIncome:  make([]float64, 12),
		MonthlyExpense: make([]float64, 12),
	}

	// 查询收入数据
	incomeQuery := `
        SELECT month, SUM(money) as total
        FROM ` + h.tableName + `
        WHERE year = ? AND type = 'income' AND del = 0
        GROUP BY month
        ORDER BY month`

	rows, err := h.db.Query(incomeQuery, year)
	if err != nil {
		return stats, err
	}
	defer rows.Close()

	for rows.Next() {
		var month string
		var total float64
		if err := rows.Scan(&month, &total); err != nil {
			return stats, err
		}
		// 将月份字符串转换为数组索引（1-12 -> 0-11）
		monthIndex := parseInt(month) - 1
		if monthIndex >= 0 && monthIndex < 12 {
			stats.MonthlyIncome[monthIndex] = total
		}
	}

	// 查询支出数据
	expenseQuery := `
        SELECT month, SUM(money) as total
        FROM ` + h.tableName + `
        WHERE year = ? AND type = 'expense' AND del = 0
        GROUP BY month
        ORDER BY month`

	rows, err = h.db.Query(expenseQuery, year)
	if err != nil {
		return stats, err
	}
	defer rows.Close()

	for rows.Next() {
		var month string
		var total float64
		if err := rows.Scan(&month, &total); err != nil {
			return stats, err
		}
		monthIndex := parseInt(month) - 1
		if monthIndex >= 0 && monthIndex < 12 {
			stats.MonthlyExpense[monthIndex] = total
		}
	}

	return stats, nil
}

func (h *StatisticsHandler) getTypeDistribution(year string) ([]TypeDistribution, error) {
	// 收入暖色系
	incomeColors := []string{"#ee6666", "#f97c5e", "#fa7f55", "#fdae6b", "#fd8d3c", "#fc8d59"}
	// 支出冷色系
	expenseColors := []string{"#91cc75", "#5470c6", "#73c0de", "#3ba272", "#5c9ead", "#7eb0d5"}
	
	// 收入类型计数器
	incomeCount := 0
	// 支出类型计数器
	expenseCount := 0
	
	query := `
	SELECT sub_type, type, SUM(money) as total
	FROM ` + h.tableName + `
	WHERE year = ? AND del = 0
	GROUP BY sub_type, type
	ORDER BY total DESC`
	
	rows, err := h.db.Query(query, year)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	
	var distribution []TypeDistribution
	for rows.Next() {
		var subType, transType string
		var total float64
		if err := rows.Scan(&subType, &transType, &total); err != nil {
			return nil, err
		}
		
		// 确定颜色
		var color string
		if transType == "income" {
			color = incomeColors[incomeCount % len(incomeColors)]
			incomeCount++
		} else {
			color = expenseColors[expenseCount % len(expenseColors)]
			expenseCount++
		}
		
		// 添加类型和颜色信息
		distribution = append(distribution, TypeDistribution{
			Name:  subType,
			Value: total,
			Type:  transType,
			Color: color,
		})
	}
	
	return distribution, nil
}

// parseInt 辅助函数：将字符串转换为整数
func parseInt(s string) int {
	var result int
	for _, ch := range s {
		if ch >= '0' && ch <= '9' {
			result = result*10 + int(ch-'0')
		}
	}
	return result
}

// MonthlyDetail 月度详情数据结构
type MonthlyDetail struct {
	TotalIncome  float64             `json:"totalIncome"`
	TotalExpense float64             `json:"totalExpense"`
	Details      []TransactionDetail `json:"details"`
}

// TransactionDetail 交易详情数据结构
type TransactionDetail struct {
	Date    string  `json:"date"`
	Type    string  `json:"type"`
	SubType string  `json:"sub_type"`
	Money   float64 `json:"money"`
	Remark  *string `json:"remark"` // 修改为指针类型，可以处理 NULL 值
}

func (h *StatisticsHandler) HandleMonthlyDetail(w http.ResponseWriter, r *http.Request) {
	// 打印请求信息
	log.Printf("收到月度详情请求 - URL: %s, 方法: %s\n", r.URL.String(), r.Method)

	if r.Method != http.MethodGet {
		log.Printf("错误：不支持的请求方法 %s\n", r.Method)
		writeJSON(w, map[string]interface{}{
			"success": false,
			"message": "方法不允许",
		}, http.StatusMethodNotAllowed)
		return
	}

	// 获取查询参数
	year := r.URL.Query().Get("year")
	month := r.URL.Query().Get("month")
	log.Printf("请求参数 - 年份: %s, 月份: %s\n", year, month)

	if year == "" || month == "" {
		log.Println("错误：缺少年份或月份参数")
		writeJSON(w, map[string]interface{}{
			"success": false,
			"message": "缺少年份或月份参数",
		}, http.StatusBadRequest)
		return
	}

	// 查询月度详情数据
	query := `
        SELECT DATE_FORMAT(create_time, '%Y-%m-%d %H:%i:%s') as date,
               type,
               sub_type,
               money,
               CASE 
                    WHEN name <> remark THEN CONCAT_WS(' ', name, remark) 
                    ELSE name 
                END AS remark
        FROM ` + h.tableName + `
        WHERE year = ? AND month = ? AND del = 0
        ORDER BY money desc`

	log.Printf("执行SQL查询 - 月度详情:\n%s\n参数: [%s, %s]\n", query, year, month)

	rows, err := h.db.Query(query, year, month)
	if err != nil {
		log.Printf("月度详情查询出错: %v\n", err)
		writeJSON(w, map[string]interface{}{
			"success": false,
			"message": "获取月度详情数据失败: " + err.Error(),
		}, http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	var details []TransactionDetail
	var totalIncome, totalExpense float64

	for rows.Next() {
		var detail TransactionDetail
		var remark sql.NullString // 使用 sql.NullString 来处理可能为 NULL 的字符串
		if err := rows.Scan(&detail.Date, &detail.Type, &detail.SubType, &detail.Money, &remark); err != nil {
			log.Printf("处理月度详情数据失败: %v\n", err)
			writeJSON(w, map[string]interface{}{
				"success": false,
				"message": "处理月度详情数据失败: " + err.Error(),
			}, http.StatusInternalServerError)
			return
		}

		// 如果 remark 有值，则使用该值；否则使用空字符串
		if remark.Valid {
			detail.Remark = &remark.String
		} else {
			emptyString := ""
			detail.Remark = &emptyString
		}

		details = append(details, detail)

		// 计算总收入和总支出
		if detail.Type == "income" {
			totalIncome += detail.Money
		} else {
			totalExpense += detail.Money
		}
	}

	monthlyDetail := MonthlyDetail{
		TotalIncome:  totalIncome,
		TotalExpense: totalExpense,
		Details:      details,
	}

	// 返回月度详情数据
	writeJSON(w, map[string]interface{}{
		"success": true,
		"data":    monthlyDetail,
	}, http.StatusOK)
}
